﻿using System;
using System.Globalization;
using System.Text;
using System.Web.UI;
using StampController.BL;
using StampController.BL.Models;

namespace StampController.Pages
{
    public partial class AdminConfirmForm : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Request.QueryString["q"]))
            {
                Response.Redirect("/");
                return;
            }

            var im = new RequestFormImpl();
            var model = im.GetRequestForm(Request.QueryString["q"]);
            if (model == null)
            {
                Response.Redirect("/");
                return;
            }

            if (!IsPostBack)
            {
                lblDepartment.Text = model.DeptName + "&nbsp;";
                lblDateOfApp.Text = model.DateRequestText + "&nbsp;";
                lblNeededDate.Text = model.DateNeededText + "&nbsp;";
                lblPagesNo.Text = model.PagesNo + "&nbsp;";
                lblCopiesNo.Text = model.CopiesNo + "&nbsp;";
                lblRemark.Text = model.Remark;
                litPurpose.Text = model.Purpose;
                litRequiredBy.Text = model.RequiredByName + (string.IsNullOrEmpty(model.DefineName) ? "&nbsp;" : string.Format(" ({0})", model.DefineName));
                litStampedType.Text = model.STName + "&nbsp;";
                litStamp.Text = model.StampName + "&nbsp;";
                litSignBy.Text = model.SignByName + "&nbsp;";
                litRequestType.Text = model.RequestTypeName + "&nbsp;";
                litCategory.Text = model.CateName;
                litRequestFor.Text = model.RequestForName;
                hdUserRequest.Value = model.RequestFor ?? model.UserID;
                hdKindOfStamp.Value = model.StampID.ToString(CultureInfo.InvariantCulture);

                // Set current user
                var currentUser = SessionUtils.Get<UsersModel>("USER");
                // Get delegate user
                UsersModel delegateUser = GetDelegateAdmin(currentUser.UserID, model.StampID) ?? currentUser;
                if (delegateUser.SiteID != model.StampID)
                {
                    Response.Redirect("/");
                    return;
                }
            }

            var htmlBuilder = new StringBuilder("<table>")
                    .Append("<thead><tr>")
                    .Append("<th class='head-left'>Document attachments:</th>")
                //.Append("<th>Pages</th>")
                //.Append("<th>Copies</th>")
                    .Append("</tr></thead>")
                    .Append("<tbody>");

            if (model.DocumentList != null)
            {
                foreach (var documentModel in model.DocumentList)
                {
                    htmlBuilder.AppendFormat("<tr><td><a href='{0}' target='_blank'>{1}</a></td>", documentModel.Link,
                        documentModel.OriginName);
                    //.AppendFormat("<td class='col-right'>{0}</td>", documentModel.PagesNo)
                    //.AppendFormat("<td class='col-right'>{0}</td></tr>", documentModel.CopiesNo);
                }
            }

            htmlBuilder.Append("</tbody>")
                .Append("</table>");
            pnlUploadFiles.Controls.Add(new LiteralControl(htmlBuilder.ToString()));

            var historyList = new ApprovalHistoryImpl().GetApprovalHistoryList(Request.QueryString["q"]);
            if (historyList.Count > 0)
            {
                htmlBuilder = new StringBuilder("<table>")
                    .Append("<thead>")
                    .Append("<tr><th>Approved By</th>")
                    .Append("<th>Approved Date</th>")
                    .Append("<th>Comment</th>")
                    .Append("<th>Status</th></tr>")
                    .Append("</thead>")
                    .Append("<tbody>");

                foreach (var approvalHistoryModel in historyList)
                {
                    htmlBuilder.AppendFormat("<tr><td>{0}</td>", approvalHistoryModel.ApprovedBy)
                        .AppendFormat("<td class='col-right'>{0}</td>", approvalHistoryModel.ApprovedDate)
                        .AppendFormat("<td>{0}</td>", approvalHistoryModel.Comment)
                        .AppendFormat("<td>{0}</td></tr>", approvalHistoryModel.StatusName);
                }

                htmlBuilder.Append("</tbody>")
                    .Append("</table>");

                pnlApprovalHistory.Controls.Add(new LiteralControl(htmlBuilder.ToString()));
            }
        }

        /// <summary>
        /// Close request by admin
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void closeButton_Click(object sender, EventArgs e)
        {
            var requestId = Request.QueryString["q"];
            var im = new RequestFormImpl();
            var result = im.CloseRequestForm(requestId, UserName, DateTime.Now);
            if (result)
            {
                Response.Redirect("/Pages/PendingConfirmList.aspx");
            }
        }

        private UsersModel GetDelegateAdmin(string userId, int? siteId)
        {
            var imAuthorized = new AuthorizedHistoryImpl();
            return imAuthorized.GetDelegateAdmin(userId, DateTime.Now, siteId);
        }
    }
}